﻿using System.Text;

namespace Tool.Utils
{
    public static class SshHelper
    {
        public static string ExecuteCommand(this SshConnectionPool sshConnectionPool, string command)
        {
            var client = sshConnectionPool.GetConnection();
            try
            {
                var result = client.RunCommand(command);
                client.Disconnect();
                if (result.ExitStatus == 0)
                {
                    return result.Result.Trim();
                }
                else
                {
                    return $"命令执行失败: {result.Error}";
                }
            }
            catch (Exception ex)
            {
                return $"命令执行失败: {ex.Message}";
            }

            finally
            {
                sshConnectionPool.ReturnConnection(client);
            }

        }


        public static string GetSystemInfo(this SshConnectionPool sshConnectionPool)
        {
            var commands = new[]
            {
                "uname -a",
                "cat /etc/os-release",
                "df -h",
                "free -m",
                "uptime"
            };

            var result = new StringBuilder();

            foreach (var command in commands)
            {
                try
                {
                    var output = sshConnectionPool.ExecuteCommand(command);
                    result.AppendLine($"=== {command} ===");
                    result.AppendLine(output);
                    result.AppendLine();
                }
                catch (Exception ex)
                {
                    result.AppendLine($"执行 {command} 失败: {ex.Message}");
                }
            }

            return result.ToString();
        }
    }
}
